#!/bin/bash

Install_Zookeeper() {
  Echo_Info "====== Installing Zookeeper ======"
  Echo_Info "Install ${Zookeeper_Ver} Version..."
  Press_Start
  cd ${cur_dir}/src

  # TODO 判断是否已经安装了zookeeper

  # 下载安装包并解压
  Download_Files ${YUSP_Download_Mirror}/zookeeper-${Zookeeper_Ver}.tar.gz zookeeper-${Zookeeper_Ver}.tar.gz
  Tar_Cd zookeeper-${Zookeeper_Ver}.tar.gz zookeeper-${Zookeeper_Ver}
  pwd
  cd ${cur_dir}/src
  # 拷贝到安装目录
  echo "mv zookeeper-${Zookeeper_Ver} to /usr/local ..."
  rm -rf /usr/local/zookeeper-${Zookeeper_Ver}
  mv ./zookeeper-${Zookeeper_Ver} /usr/local/
  # 配置环境变量
  cd /usr/local/zookeeper-${Zookeeper_Ver}
  ZOOKEEPER_HOME=$(pwd)
  echo "add ZOOKEEPER_HOME TO /etc/profile ..."
  cat >>/etc/profile <<EOF
#ZOOKEEPER_HOME
export ZOOKEEPER_HOME=${ZOOKEEPER_HOME}
export PATH=\$PATH:${ZOOKEEPER_HOME}/bin
EOF
  source /etc/profile

  # 修改配置文件
  cd /usr/local/zookeeper-${Zookeeper_Ver}/conf
  mv zoo_sample.cfg zoo.cfg
  mkdir /usr/local/zookeeper-${Zookeeper_Ver}/data
  sed -i "s#/tmp/zookeeper#/usr/local/zookeeper-${Zookeeper_Ver}/data#" zoo.cfg
  cat >>zoo.cfg <<EOF
#集群地址
server.0=localhost:2888:3888
EOF
  cd /usr/local/zookeeper-${Zookeeper_Ver}/data
  cat >>myid <<EOF
0
EOF

  # 启动zookeeper
  /usr/local/zookeeper-${Zookeeper_Ver}/bin/zkServer.sh start
  /usr/local/zookeeper-${Zookeeper_Ver}/bin/zkServer.sh status
  if [ $? -eq 0 ]; then
    Echo_Green "OK, ====== Zookeeper_Install Successful!!======"
  else
    Echo_Red "Sorry, Zookeeper_Install failed! please check you operation and try again!"
    return -1
  fi

}

Uninstall_Zookeeper() {
  echo "You will uninstall Zookeeper..."
  echo "Shutting down Zookeeper..."
  # 杀掉zookeeper进程
  zookeeper_pid=`ps -ef|grep QuorumPeerMain | grep -v color|awk '{print $2}'`
  kill $zookeeper_pid
  # 删除安装文件
  rm -rf /usr/local/zookeeper*

  # 删除环境变量
  echo "Delete ZOOKEEPER_HOME in /etc/profile ..."
  sed -i '/zookeeper/d' /etc/profile
  sed -i '/ZOOKEEPER_HOME/d' /etc/profile
  source /etc/profile
  Echo_Green "Uninstall Zookeeper completed."
}
